<template>
    <div class="container mx-auto p-4">
        <!-- 基本信息卡片 -->
        <el-card class="mb-6 shadow-md">
            <div slot="header" class="font-semibold text-lg">项目基本信息</div>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="项目名称">{{
                    basicInfo.projectName
                }}</el-descriptions-item>
                <el-descriptions-item label="合同编号">{{
                    basicInfo.contractNo
                }}</el-descriptions-item>
                <el-descriptions-item label="施工单位">{{
                    basicInfo.constructionUnit
                }}</el-descriptions-item>
                <el-descriptions-item label="建设单位">{{
                    basicInfo.developmentUnit
                }}</el-descriptions-item>
                <el-descriptions-item label="结算日期">{{
                    basicInfo.settlementDate
                }}</el-descriptions-item>
                <el-descriptions-item label="负责人">{{
                    basicInfo.responsiblePerson
                }}</el-descriptions-item>
            </el-descriptions>
        </el-card>

        <!-- 顶部功能按钮 -->
        <div class="flex justify-between mb-4 flex-wrap gap-2">
            <div class="flex gap-2">
                <el-button
                    type="primary"
                    icon="RefreshRight"
                    class="transition-all hover:shadow-lg"
                    @click="generateVerification"
                >
                    生成校验
                </el-button>
                <el-button
                    type="success"
                    icon="Download"
                    class="transition-all hover:shadow-lg"
                    @click="exportReport"
                >
                    导出报告
                </el-button>
            </div>
            <el-button
                type="default"
                icon="ArrowLeft"
                class="transition-all hover:shadow-lg"
                @click="handleBack"
            >
                返回
            </el-button>
        </div>

        <!-- 统计图表区域：概览 + 环形图 + 竖向柱状图 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <!-- 1. 校验结果概览 -->
            <el-card class="shadow-md">
                <div slot="header" class="font-semibold">校验结果概览</div>
                <div class="p-4 space-y-4">
                    <div class="space-y-2">
                        <div class="flex items-center justify-between">
                            <span class="flex items-center">
                                <span
                                    class="inline-block w-3 h-3 bg-green-500 rounded-full mr-2"
                                ></span>
                                通过数量
                            </span>
                            <span class="font-bold text-lg">{{
                                passCount
                            }}</span>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="flex items-center">
                                <span
                                    class="inline-block w-3 h-3 bg-red-500 rounded-full mr-2"
                                ></span>
                                未通过数量
                            </span>
                            <span class="font-bold text-lg">{{
                                failCount
                            }}</span>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="flex items-center">
                                <span
                                    class="inline-block w-3 h-3 bg-gray-500 rounded-full mr-2"
                                ></span>
                                总校验项
                            </span>
                            <span class="font-bold text-lg">{{
                                totalCount
                            }}</span>
                        </div>
                    </div>
                    <div>
                        <div
                            class="flex justify-between text-sm text-gray-500 mb-1"
                        >
                            <span>通过率</span>
                            <span>{{ passRate }}%</span>
                        </div>
                        <el-progress
                            :percentage="passRate"
                            type="line"
                            stroke-width="6"
                            :status="passRate >= 80 ? 'success' : 'exception'"
                        />
                    </div>
                </div>
            </el-card>

            <!-- 2. 校验结果分布（环形图） -->
            <el-card class="shadow-md">
                <div slot="header" class="font-semibold">校验结果分布</div>
                <div class="p-4" style="height: 240px">
                    <div
                        ref="resultPieChart"
                        style="width: 100%; height: 100%"
                    ></div>
                </div>
            </el-card>

            <!-- 3. 校验类型分布（柱状图 - 重点修复） -->
            <el-card class="shadow-md">
                <div
                    slot="header"
                    class="font-semibold flex items-center justify-between"
                >
                    <span>校验类型分布</span>
                    <span class="text-xs text-gray-500"
                        >总计：{{ typeTotalCount }} 项</span
                    >
                </div>
                <!-- 图表容器：使用固定宽高 + 背景色，便于排查是否渲染 -->
                <div
                    class="p-4"
                    style="height: 240px; background-color: #f9fafb"
                >
                    <!-- 图表未加载时显示提示 -->
                    <div
                        v-if="!isBarChartRendered"
                        class="w-full h-full flex flex-col items-center justify-center text-gray-400 text-sm"
                    >
                        <el-loading-spinner
                            size="20"
                            class="mb-2"
                        ></el-loading-spinner>
                        <span>图表加载中...</span>
                    </div>
                    <!-- 图表容器：添加id便于调试，固定宽高 -->
                    <div
                        id="typeBarChart"
                        ref="typeBarChart"
                        style="width: 100%; height: 100%; display: none"
                    ></div>
                </div>
            </el-card>
        </div>

        <!-- 校验信息表格 -->
        <el-card class="shadow-md">
            <div
                slot="header"
                class="font-semibold text-lg flex justify-between items-center"
            >
                <span>校验信息</span>
                <span class="text-sm text-gray-500"
                    >共 {{ totalCount }} 条校验记录</span
                >
            </div>
            <el-table
                :data="verificationData"
                border
                class="w-full shadow-sm"
                size="small"
                highlight-current-row
            >
                <el-table-column
                    prop="index"
                    label="序号"
                    width="60"
                    align="center"
                />
                <el-table-column
                    prop="fileName"
                    label="文件名"
                    align="center"
                />
                <el-table-column
                    prop="verifyType"
                    label="校验类型"
                    align="center"
                />
                <el-table-column
                    prop="verifyItem"
                    label="校验项"
                    align="center"
                />
                <el-table-column label="状态" align="center">
                    <template #default="scope">
                        <el-tag
                            type="success"
                            v-if="scope.row.status === 'pass'"
                            size="small"
                            >通过</el-tag
                        >
                        <el-tag
                            type="danger"
                            v-if="scope.row.status === 'error'"
                            size="small"
                            >未通过</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column
                    prop="errorInfo"
                    label="错误信息"
                    align="center"
                    :show-overflow-tooltip="true"
                />
                <el-table-column label="操作" align="center" width="180">
                    <template #default="scope">
                        <el-button
                            type="text"
                            icon="Edit"
                            @click="handleProcess(scope.row)"
                            class="text-primary p-0"
                            size="small"
                            >处理</el-button
                        >
                        <el-button
                            type="text"
                            icon="Check"
                            @click="handleConfirm(scope.row)"
                            class="text-success p-0"
                            size="small"
                            >确认</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
    RefreshRight,
    Download,
    ArrowLeft,
    Edit,
    Check,
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";

// -------------------------- 1. 确保ECharts依赖正确引入 --------------------------
// 方式1：如果项目已npm安装echarts，直接引入（推荐）
let echarts = null;
try {
    // 尝试引入本地安装的echarts
    echarts = require("echarts");
    // 验证核心模块是否存在
    if (!echarts || !echarts.init) {
        throw new Error("ECharts核心模块缺失");
    }
} catch (error) {
    console.error("本地ECharts加载失败，尝试加载CDN:", error);
    // 方式2：本地加载失败时，动态加载CDN
    const loadEchartsCDN = () => {
        return new Promise((resolve, reject) => {
            if (window.echarts) {
                echarts = window.echarts;
                resolve(echarts);
                return;
            }
            const script = document.createElement("script");
            script.src =
                "https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js";
            script.onload = () => {
                echarts = window.echarts;
                resolve(echarts);
            };
            script.onerror = () => reject(new Error("CDN ECharts加载失败"));
            document.head.appendChild(script);
        });
    };
    // 加载CDN并提示用户
    loadEchartsCDN()
        .then(() => {
            ElMessage.success("ECharts图表库加载成功");
        })
        .catch((err) => {
            ElMessage.error("图表加载失败，请刷新页面重试");
            console.error(err);
        });
}

// -------------------------- 2. 基础数据与统计计算 --------------------------
const router = useRouter();

// 项目基础信息
const basicInfo = reactive({
    projectName: "国家管网维抢修中心后勤标准化建设项目",
    contractNo: "GWLH34-2024-209",
    constructionUnit: "宣垣建设集团有限公司",
    developmentUnit: "西部塔里木输油气分公司",
    settlementDate: "2024-05-15",
    responsiblePerson: "张三",
});

// 校验数据（固定数据，确保图表有数据可渲染）
const verificationData = ref([
    {
        index: 1,
        fileName: "竣工结算通知书",
        verifyType: "完整性",
        verifyItem: "文件存在性校验",
        status: "error",
        errorInfo: '资料中缺失"竣工结算通知书"文件，请上传',
    },
    {
        index: 2,
        fileName: "工程量计算表",
        verifyType: "合规性",
        verifyItem: "工作量校验",
        status: "error",
        errorInfo: "天棚面龙骨及饰面拆除数量不一致，请核对",
    },
    {
        index: 3,
        fileName: "工程施工水电确认单",
        verifyType: "合规性",
        verifyItem: "文件有效性校验",
        status: "error",
        errorInfo: "缺失甲方财务部门盖章",
    },
    {
        index: 4,
        fileName: "工程施工水电确认单",
        verifyType: "合规性",
        verifyItem: "日期合规性校验",
        status: "error",
        errorInfo: "合同完工时间小于实际完工时间，请核实",
    },
    {
        index: 5,
        fileName: "工作量确认单",
        verifyType: "合规性",
        verifyItem: "文件有效性校验",
        status: "error",
        errorInfo: "缺失甲方财务部门盖章",
    },
    {
        index: 6,
        fileName: "工作量确认单",
        verifyType: "合规性",
        verifyItem: "工作量校验",
        status: "error",
        errorInfo: "抹灰面油漆计算公式错误，请更正",
    },
    {
        index: 7,
        fileName: "工程预算表",
        verifyType: "合规性",
        verifyItem: "价格校验",
        status: "pass",
        errorInfo: "",
    },
    {
        index: 8,
        fileName: "费用明细表",
        verifyType: "合规性",
        verifyItem: "费用校验",
        status: "error",
        errorInfo: "部分费用超出预算标准",
    },
    {
        index: 9,
        fileName: "水电费缴纳凭证",
        verifyType: "合规性",
        verifyItem: "水电费扣款校验",
        status: "error",
        errorInfo: "水电费计算方式与合同不符",
    },
    {
        index: 10,
        fileName: "验收报告",
        verifyType: "合规性",
        verifyItem: "其它",
        status: "pass",
        errorInfo: "",
    },
]);

// 统计计算（确保数据不为空）
const passCount = computed(
    () => verificationData.value.filter((item) => item.status === "pass").length
);
const failCount = computed(
    () =>
        verificationData.value.filter((item) => item.status === "error").length
);
const totalCount = computed(() => verificationData.value.length);
const passRate = computed(() =>
    totalCount.value > 0
        ? Math.round((passCount.value / totalCount.value) * 100)
        : 0
);
// 校验类型统计（确保至少有2个类型数据）
const typeCount = computed(() => {
    const count = {
        完整性: verificationData.value.filter(
            (item) => item.verifyType === "完整性"
        ).length,
        合规性: verificationData.value.filter(
            (item) => item.verifyType === "合规性"
        ).length,
    };
    // 兜底：如果某个类型数量为0，强制设为1（避免图表无数据）
    if (count.完整性 === 0) count.完整性 = 1;
    if (count.合规性 === 0) count.合规性 = 1;
    return count;
});
const typeTotalCount = computed(() =>
    Object.values(typeCount.value).reduce((sum, val) => sum + val, 0)
);
const typeAvgCount = computed(() =>
    typeTotalCount.value > 0
        ? Math.round(typeTotalCount.value / Object.keys(typeCount.value).length)
        : 0
);

// -------------------------- 3. 图表状态与初始化（重点修复） --------------------------
// 图表实例与渲染状态
const resultPieChart = ref(null);
const typeBarChart = ref(null);
const pieChartInstance = ref(null);
const barChartInstance = ref(null);
const isBarChartRendered = ref(false); // 标记柱状图是否渲染成功

// 监听ECharts加载完成，触发图表初始化
const checkEchartsReady = () => {
    return new Promise((resolve) => {
        const checkInterval = setInterval(() => {
            if (echarts && echarts.init) {
                clearInterval(checkInterval);
                resolve(true);
            }
        }, 100);
        // 超时兜底（5秒后停止检查）
        setTimeout(() => {
            clearInterval(checkInterval);
            resolve(false);
        }, 5000);
    });
};

// 初始化环形图（作为参考，验证ECharts是否正常工作）
const initPieChart = async () => {
    const isReady = await checkEchartsReady();
    if (!isReady || !resultPieChart.value) {
        console.error("环形图初始化失败：ECharts未就绪或DOM不存在");
        return;
    }

    try {
        const chart = echarts.init(resultPieChart.value);
        pieChartInstance.value = chart;
        const option = {
            tooltip: { trigger: "item", formatter: "{b}: {c} 项 ({d}%)" },
            legend: {
                orient: "horizontal",
                bottom: 0,
                left: "center",
                data: ["通过", "未通过"],
            },
            series: [
                {
                    name: "校验结果",
                    type: "pie",
                    radius: ["45%", "70%"],
                    center: ["50%", "40%"],
                    data: [
                        {
                            value: passCount.value,
                            name: "通过",
                            itemStyle: { color: "#10b981" },
                        },
                        {
                            value: failCount.value,
                            name: "未通过",
                            itemStyle: { color: "#ef4444" },
                        },
                    ],
                },
            ],
        };
        chart.setOption(option);
        // 窗口resize重绘
        window.addEventListener("resize", () => chart.resize());
        console.log("环形图初始化成功");
    } catch (error) {
        console.error("环形图初始化异常:", error);
        ElMessage.error("环形图加载失败");
    }
};

// 初始化柱状图（核心修复）
const initBarChart = async () => {
    const isReady = await checkEchartsReady();
    if (!isReady || !typeBarChart.value) {
        console.error("柱状图初始化失败：ECharts未就绪或DOM不存在");
        return;
    }

    try {
        // 1. 先显示DOM容器
        typeBarChart.value.style.display = "block";
        // 2. 初始化图表（确保DOM已显示，能正确计算尺寸）
        const chart = echarts.init(typeBarChart.value);
        barChartInstance.value = chart;

        // 3. 简化图表配置（先确保基础渲染，再逐步添加复杂功能）
        const option = {
            tooltip: { trigger: "axis", formatter: "{b}: {c} 项" },
            // 简化grid：确保不遮挡坐标轴
            grid: {
                left: "15%",
                right: "10%",
                bottom: "20%",
                top: "20%",
                containLabel: true,
            },
            xAxis: {
                type: "category",
                data: Object.keys(typeCount.value),
                axisLabel: { fontSize: 12, color: "#333" },
            },
            yAxis: {
                type: "value",
                min: 0,
                axisLabel: {
                    formatter: "{value} 项",
                    fontSize: 12,
                    color: "#333",
                },
                splitLine: { lineStyle: { type: "dashed", color: "#eee" } },
            },
            series: [
                {
                    name: "校验项数量",
                    type: "bar",
                    data: Object.values(typeCount.value),
                    barWidth: "50%",
                    itemStyle: { color: "#3b82f6" }, // 纯色优先，避免渐变问题
                    label: { show: true, position: "top", color: "#333" },
                },
            ],
        };

        // 4. 设置配置并验证渲染
        chart.setOption(option);
        // 5. 标记渲染成功
        isBarChartRendered.value = true;
        // 6. 窗口resize重绘
        window.addEventListener("resize", () => chart.resize());

        console.log("柱状图初始化成功", {
            data: Object.values(typeCount.value),
            domSize: {
                width: typeBarChart.value.offsetWidth,
                height: typeBarChart.value.offsetHeight,
            },
        });
        ElMessage.success("校验类型分布图表加载成功");
    } catch (error) {
        console.error("柱状图初始化异常:", error);
        ElMessage.error("柱状图加载失败，请刷新页面");
        // 异常时显示错误提示
        isBarChartRendered.value = false;
        typeBarChart.value.style.display = "none";
    }
};

// -------------------------- 4. 生命周期与事件监听 --------------------------
onMounted(() => {
    // 等待DOM完全渲染
    nextTick(() => {
        console.log("DOM渲染完成，开始初始化图表", {
            pieDom: resultPieChart.value,
            barDom: typeBarChart.value,
        });
        // 先初始化环形图，再初始化柱状图
        initPieChart();
        // 延迟初始化柱状图，避免资源竞争
        setTimeout(initBarChart, 500);
    });
});

// 监听typeCount变化，刷新柱状图数据
watch(typeCount, () => {
    if (barChartInstance.value) {
        barChartInstance.value.setOption({
            series: [
                {
                    data: Object.values(typeCount.value),
                },
            ],
        });
    }
});

// 组件卸载时清理
onUnmounted(() => {
    window.removeEventListener("resize", () => {
        pieChartInstance.value && pieChartInstance.value.resize();
        barChartInstance.value && barChartInstance.value.resize();
    });
    // 销毁图表实例，释放资源
    pieChartInstance.value && pieChartInstance.value.dispose();
    barChartInstance.value && barChartInstance.value.dispose();
});

// -------------------------- 5. 业务逻辑（保持不变） --------------------------
const handleBack = () => {
    router.back();
    ElMessage.info("返回上一页");
};

const generateVerification = () => {
    ElMessageBox.confirm(
        "确定要重新生成校验结果吗？这将覆盖当前校验信息。",
        "确认操作",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            center: true,
        }
    )
        .then(() => {
            ElMessage({ type: "info", message: "正在生成校验结果..." });
            setTimeout(() => {
                ElMessage({ type: "success", message: "校验结果生成成功" });
                // 重新初始化图表
                initPieChart();
                initBarChart();
            }, 1500);
        })
        .catch(() => {
            ElMessage({ type: "info", message: "已取消生成操作" });
        });
};

const exportReport = () => {
    ElMessage({ type: "info", message: "正在准备导出文件..." });
    setTimeout(() => {
        ElMessage({ type: "success", message: "校验报告已导出至本地" });
    }, 1500);
};

const handleProcess = (row) => {
    ElMessageBox.prompt(
        `请输入"${row.fileName}"的【${row.verifyItem}】问题处理说明：`,
        "处理校验问题",
        { inputType: "textarea", inputRows: 3, center: true }
    )
        .then(({ value }) => {
            if (!value.trim()) return ElMessage.error("处理说明不能为空");
            ElMessage({
                type: "success",
                message: `处理说明已提交：${value.slice(0, 20)}...`,
            });
        })
        .catch(() => {
            ElMessage({ type: "info", message: "已取消处理操作" });
        });
};

const handleConfirm = (row) => {
    ElMessageBox.confirm(
        `确定要确认"${row.fileName}"的【${row.verifyItem}】校验结果吗？`,
        "确认结果",
        { type: row.status === "pass" ? "success" : "warning", center: true }
    )
        .then(() => {
            ElMessage.success(`已确认 ${row.fileName} 的校验结果`);
        })
        .catch(() => {
            ElMessage.info("已取消确认操作");
        });
};
</script>

<style scoped>
/* 基础样式 */
.el-card,
.el-table {
    @apply transition-all duration-300;
}
.el-button {
    @apply hover:shadow-md;
}

/* 图表容器样式加固（确保不被隐藏） */
#typeBarChart,
.echarts-container {
    @apply opacity-100 !important;
    z-index: 1 !important;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
    .grid {
        @apply gap-6;
    }
    .el-card .p-4 {
        @apply p-2;
    }
    /* 小屏幕下图表高度适配 */
    .el-card:nth-child(2) .p-4,
    .el-card:nth-child(3) .p-4 {
        @apply h-[220px] !important;
    }
}
</style>
